package lc20240501;

import java.util.HashMap;
import java.util.Map;

//76. 最小覆盖子串
public class Demo2 {
    public static void main(String[] args) {
        String s="ADOBECODEBANC";
        String t="ABC";
        System.out.println(minWindow(s, t));
    }
    public static String minWindow(String s, String t) {
        if (s == null || s.isEmpty() || t == null || t.isEmpty()) {
            return "";
        }

        Map<Character, Integer> targetFreq = new HashMap<>();
        for (char c : t.toCharArray()) {
            targetFreq.put(c, targetFreq.getOrDefault(c, 0) + 1);
        }

        int left = 0, right = 0;
        int minLength = Integer.MAX_VALUE;
        int start = 0;
        int remaining = t.length();

        while (right < s.length()) {
            char c = s.charAt(right);
            if (targetFreq.containsKey(c)) {
                if (targetFreq.get(c) > 0) {
                    remaining--;
                }
                targetFreq.put(c, targetFreq.get(c) - 1);
            }
            right++;

            while (remaining == 0) {
                if (right - left < minLength) {
                    minLength = right - left;
                    start = left;
                }

                char leftChar = s.charAt(left);
                if (targetFreq.containsKey(leftChar)) {
                    targetFreq.put(leftChar, targetFreq.get(leftChar) + 1);
                    if (targetFreq.get(leftChar) > 0) {
                        remaining++;
                    }
                }
                left++;
            }
        }

        return minLength == Integer.MAX_VALUE ? "" : s.substring(start, start + minLength);
    }
}
